<script setup lang="tsx">
import { nextTick, ref, unref } from 'vue'
import {
  selectByModelApi,
  selectPageByIdApi,
  saveByModelApi,
  updateByModelApi,
  deleteByModelApi
} from '@/api/sysGenPage'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { useSearch } from '@/hooks/web/useSearch'
import { useRoute } from 'vue-router'
import VFormRender from '@/components/variant-form3/form-render/index.vue'
import { ElMessage } from 'element-plus'
const { t } = useI18n()
const { query } = useRoute()
const pageId = ref(query.pageId)
const { searchRegister, searchMethods } = useSearch()
const { getFormData } = searchMethods
const id = ref<string>()
const pageData = ref()
const formJson = ref()
const optionData = ref()
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    if (!pageData.value || !pageData.value.genModel.id) {
      return {
        list: [],
        total: 0
      }
    }
    const formData = await getFormData()
    const queryData = {
      modelId: pageData.value ? pageData.value.genModel.id : '',
      queryFields: {},
      page: { size: unref(pageSize), current: unref(currentPage) }
    }
    const queryFields = {}
    if (searchSchema.value && searchSchema.value.length > 0) {
      searchSchema.value.forEach((item: FormSchema) => {
        queryFields[item.field] = formData[item.field]
      })
    }
    queryData.queryFields = queryFields
    const res = await selectByModelApi(queryData)
    console.log('res', res)
    return {
      list: res.result ? res.result.records || [] : [],
      total: res.result ? res.result.total : 0
    }
  },
  fetchDelApi: async () => {
    const res = await deleteByModelApi({
      formData: { id: id.value },
      modelId: pageData.value ? pageData.value.genModel.id : ''
    })
    return !!res
  }
})
const { dataList, loading, total, currentPage, pageSize } = tableState
nextTick(() => {
  getPageData()
})
const showPreviewDialogFlag = ref(false)
const getPageData = () => {
  selectPageByIdApi({ id: pageId.value }).then((res) => {
    if (res.success) {
      pageData.value = res.result
      searchSchema.value = res.result.formSchemas
      tableColumns.value = res.result.tableColumns
      tableColumns.value.push(tableAction.value)
      tableColumns.value.unshift({
        field: 'index',
        label: t('userDemo.index'),
        type: 'index'
      })
      formJson.value = res.result.genForm
    }
    getList()
    console.log('pageData.value', pageData.value)
  })
}
const { getList, refresh, getElTableExpose, delList } = tableMethods
const tableColumns = ref()
const tableAction = ref({
  field: 'action',
  width: '260px',
  label: t('tableDemo.action'),
  slots: {
    default: (data: any) => {
      return (
        <>
          <BaseButton type="primary" onClick={() => edit(data.row, 'edit')}>
            {t('exampleDemo.edit')}
          </BaseButton>
          <BaseButton type="success" onClick={() => detail(data.row, 'detail')}>
            {t('exampleDemo.detail')}
          </BaseButton>
          <BaseButton loading={delLoading.value} type="danger" onClick={() => delData(data.row)}>
            {t('exampleDemo.del')}
          </BaseButton>
        </>
      )
    }
  }
})
const searchSchema = ref()
const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentRow = ref()
const actionType = ref('')

const saveLoading = ref(false)
const AddAction = () => {
  console.log('dataList', dataList.value)
  console.log('formJson', formJson.value)
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  showPreviewDialogFlag.value = true
  actionType.value = 'save'
  nextTick(() => {
    preForm.value.enableForm()
  })
}
const preForm = ref()
const save = async () => {
  const formData = await preForm.value.getFormData()
  const data = {
    formData: formData,
    modelId: pageData.value ? pageData.value.genModel.id : ''
  }
  if (id.value) {
    formData.id = id.value
  }
  const res =
    actionType.value === 'edit' ? await updateByModelApi(data) : await saveByModelApi(data)
  if (res.success) {
    ElMessage.success(t(res.message))
  }
  showPreviewDialogFlag.value = false
  saveLoading.value = false
  refresh()
}
const delLoading = ref(false)
const delData = async (row) => {
  await getElTableExpose()
  id.value = row.id || ''
  delLoading.value = true
  await delList(1).finally(() => {
    delLoading.value = false
  })
}
const edit = async (row, type) => {
  id.value = row.id
  dialogTitle.value = t('exampleDemo.edit')
  showPreviewDialogFlag.value = true
  nextTick(() => {
    preForm.value.enableForm()
    preForm.value.setFormData(row)
  })
  actionType.value = type
}
const detail = (row, type) => {
  id.value = row.id
  dialogTitle.value = t('exampleDemo.detail')
  showPreviewDialogFlag.value = true
  nextTick(() => {
    preForm.value.setFormData(row)
    preForm.value.disableForm()
  })
  actionType.value = type
}
</script>

<template>
  <ContentWrap>
    <Search
      :schema="searchSchema"
      @reset="setSearchParams"
      @search="setSearchParams"
      @register="searchRegister"
    />
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <Table
      showAction
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      @refresh="refresh"
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
  <el-dialog
    draggable
    :title="dialogTitle"
    v-model="showPreviewDialogFlag"
    :show-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :destroy-on-close="true"
    :append-to-body="true"
    class="drag-dialog small-padding-dialog"
    width="50%"
  >
    <div>
      <div class="form-render-wrapper">
        <VFormRender
          ref="preForm"
          :form-json="formJson"
          :preview-state="true"
          :option-data="optionData"
        />
      </div>
    </div>
    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="showPreviewDialogFlag = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </el-dialog>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Detail :current-row="currentRow" :pageData="pageData" />
    <template #footer>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
